package io.rehuo.modules.app.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.rehuo.common.exception.RRException;
import io.rehuo.common.utils.StringUtils;
import io.rehuo.modules.app.dao.BankDao;
import io.rehuo.modules.app.dao.UserBankDao;
import io.rehuo.modules.app.entity.BankEntity;
import io.rehuo.modules.app.entity.UserBankEntity;
import io.rehuo.modules.app.entity.UserEntity;
import io.rehuo.modules.app.service.UserBankService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author shiguang
 * @date 2022年09月18日 15:38
 */
@Service("userBankService")
public class UserBankServiceImpl extends ServiceImpl<UserBankDao, UserBankEntity> implements UserBankService {

    @Autowired
    private BankDao bankDao;

    @Override
    public UserBankEntity getByUserId(Long userId) {
        UserBankEntity userBankEntity = baseMapper.selectOne(new QueryWrapper<UserBankEntity>().eq("user_id", userId).eq("del_flag", false));
        if (ObjectUtil.isNotNull(userBankEntity)) {
            BankEntity bankEntity = bankDao.selectOne(new QueryWrapper<BankEntity>().eq("id", userBankEntity.getBankId()));
            userBankEntity.setName(bankEntity.getBankName());
        }
        return userBankEntity;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveUserBank(UserEntity userEntity, UserBankEntity userBank) {
        if (userBank.getBankId() == null || StringUtils.isBlank(userBank.getBankName()) || StringUtils.isBlank(userBank.getBankNo())){
            throw new RRException("params is null");
        }
        BankEntity bankEntity = bankDao.selectById(userBank.getBankId());
        userBank.setSimpleName(bankEntity.getSimpleName());
        userBank.setUserId(userEntity.getUserId());
        userBank.setCreateTime(new Date());
        baseMapper.insert(userBank);
    }
}
